#include "cabinet.h"
#include "ui_cabinet.h"
#include <QDebug>

Cabinet::Cabinet(int colNum, QString cLayout, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Cabinet)
{
    ui->setupUi(this);
    ui->tab->installEventFilter(this);
    screenIndex = -1;
    seqNum = colNum;
    editEnable = false;
    textLock = true;
    caseTexts.clear();
    initLayout(cLayout);
//    connect(ui->tab, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(tab_itemChanged(QTableWidgetItem*)));
}

void Cabinet::setCtrlSeq(unsigned int row, char ctrlWd)
{
    if(row>(unsigned int)ctrlSeq.size())
    {
        qDebug()<<"[setCtrlSeq]"<<"out of range";
        return;
    }
    ctrlSeq[row] = ctrlWd;
}

void Cabinet::setCtrlSeq(QByteArray ctrlWd)
{
    if(ctrlWd.size() != ctrlSeq.size())
    {
        qDebug()<<"[setCtrlSeq]"<<"wrong size"<<ctrlWd.size()<<ctrlSeq.size();
    }
    ctrlSeq = ctrlWd;
}

void Cabinet::setCtrlIo(unsigned int row, char ctrlWd)
{
    if(row>(unsigned int)ctrlIo.size())
    {
        qDebug()<<"[setCtrlIo]"<<"out of range";
        return;
    }
    ctrlIo[row] = ctrlWd;
}

void Cabinet::setCtrlIo(QByteArray ctrlWd)
{
    if(ctrlWd.size() != ctrlIo.size())
    {
        qDebug()<<"[setCtrlIo]"<<"wrong size";
    }
    ctrlIo = ctrlWd;
}

void Cabinet::setText(QStringList texts)
{
    int i;
    if(texts.count() != caseTexts.count())
    {
        qDebug()<<"[setText]"<<"wrong size"<<texts.count()<<caseTexts.count();
        return;
    }
    caseTexts = texts;
    updateFirstLetters(caseTexts);
    disconnect(ui->tab, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(tab_itemChanged(QTableWidgetItem*)));
    for(i=0; i<texts.count(); i++)
    {
        setText(i, texts.at(i));
    }
    connect(ui->tab, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(tab_itemChanged(QTableWidgetItem*)));
}

void Cabinet::setText(int row, QString text)
{
    if(row>rowCount())
        qDebug()<<"[set case text] out of range";

    ui->tab->item(row, 0)->setText(text);
}

QByteArray Cabinet::getCtrlSeq()
{
    qDebug()<<"getCtrlSeq"<<ctrlSeq;
    return ctrlSeq;
}

char Cabinet::getCtrlSeq(int row)
{
    return ctrlSeq.at(row);
}

QByteArray Cabinet::getCtrlIo()
{
    return ctrlIo;
}

char Cabinet::getCtrlIo(int row)
{
    return ctrlIo.at(row);
}

QStringList Cabinet::getCaseText()
{
    return caseTexts;
}

void Cabinet::setScreenPos(int row)
{
    screenIndex = row;
    ui->tab->item(row, 0)->setBackgroundColor(QColor(62, 155, 255));
}

void Cabinet::clearScreen()
{
    ui->tab->item(screenIndex, 0)->setBackgroundColor(QColor(255,255,255));
    screenIndex = -1;
}

void Cabinet::clearSelection()
{
    ui->tab->clearSelection();
}

void Cabinet::initLayout(QString cabLayout)
{
    colLayout = cabLayout;
    ui->tab->clear();
    ui->tab->setColumnCount(1);
    ui->tab->setRowCount(cabLayout.count());
//    ui->tab->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    for(int i=0; i<ui->tab->rowCount(); i++)
    {
        ui->tab->setItem(i,0,new QTableWidgetItem());
        caseTexts<<QString();
//        qDebug()<<caseTexts;
    }
    firstLetters.clear();
    searchClear();
    setEditState(false);
    cabSplit(colLayout, ui->tab);
    ctrlIo = QByteArray(cabLayout.count(),'\0');
    ctrlSeq = QByteArray(cabLayout.count(),'\0');
//    qDebug()<<"initLayout"<<ctrlSeq;
    textLock = false;
}

int Cabinet::rowCount()
{
    return ui->tab->rowCount();
}

QByteArray Cabinet::getOpenData(int row)
{
    QByteArray qba = QByteArray::fromHex("fa000100ff");
    qba[1] = ctrlSeq[row];
    qba[3] = ctrlIo[row];
    return qba;
}

void Cabinet::setEditState(bool enabled)
{
    editEnable = enabled;
    if(enabled)
        ui->tab->setEditTriggers(QTableWidget::DoubleClicked);
    else
        ui->tab->setEditTriggers(QTableWidget::NoEditTriggers);
}

int Cabinet::findGoodsByPinyin(QString py)
{
    if(firstLetters.isEmpty())
        return -1;

    int ret = -1;
    int i = 0;

    foreach(QString str, firstLetters)
    {
        qDebug()<<py<<str;
        if(str.indexOf(py,0, Qt::CaseInsensitive) != -1)
        {
            setSearchState(i, true);
            ret = 0;
//            return i;
        }
        i++;
    }
    return ret;
}

void Cabinet::searchClear()
{
    int i=0;
    disconnect(ui->tab, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(tab_itemChanged(QTableWidgetItem*)));
    for(i=0; i<ui->tab->rowCount(); i++)
    {
        if(i == screenIndex)
            continue;
        setSearchState(i, false);
    }

    connect(ui->tab, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(tab_itemChanged(QTableWidgetItem*)));
}

#include <QHeaderView>
void Cabinet::cabSplit(QString scale, QTableWidget *table)
{
    if(scale.isEmpty()||(table == NULL))
    {
        return;
    }
    int rowCount = ui->tab->rowCount();
    int baseCount = getBaseCount(scale);
    int baseHeight = (table->geometry().height())/baseCount;
    int i = 0;
//    table->setRowCount(rowCount);
//    table->setColumnCount(1);
#if QT_VERSION > 0x50000
    table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
#else
    table->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
#endif
    table->verticalHeader()->setVisible(false);
    table->horizontalHeader()->setVisible(false);
    table->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    table->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

//    qDebug()<<table->geometry().height()<<baseCount<<baseHeight;
    for(i=0; i<rowCount; i++)
    {
        table->setRowHeight(i,baseHeight*(scale.mid(i,1).toInt()));
    }
}

int Cabinet::getBaseCount(QString scale)
{
    int i = 0;
    int ret = 0;
    if(scale.isEmpty())
        return ret;

    for(i=0; i<scale.length(); i++)
    {
        ret += scale.mid(i,1).toInt();
    }
    return ret;
}

bool Cabinet::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->tab)
    {
        if(event->type() == QEvent::FocusOut)
        {
            ui->tab->clearSelection();
        }
    }
    return QWidget::eventFilter(watched, event);
}

void Cabinet::updateFirstLetters(QStringList l)
{
    firstLetters.clear();
    foreach(QString str, l)
    {
        firstLetters<<ChineseLetterHelper::GetFirstLettersAll(str);
    }
}

void Cabinet::setSearchState(int row, bool searched)
{
    if(searched)
    {
        ui->tab->item(row, 0)->setBackgroundColor(QColor(238,128,61));
    }
    else
    {
        ui->tab->item(row, 0)->setBackgroundColor(QColor("#d2dbe2"));
    }
}

void Cabinet::resizeEvent(QResizeEvent *)
{
    cabSplit(colLayout, ui->tab);
}

Cabinet::~Cabinet()
{
    delete ui;
}

void Cabinet::on_tab_cellClicked(int row, int)
{
    emit caseClicked(QPoint(seqNum, row));
}

void Cabinet::tab_itemChanged(QTableWidgetItem *item)
{
    if(textLock)
        return;

    caseTexts.removeAt(item->row());
    caseTexts.insert(item->row(), transLine(item->text()));
    updateFirstLetters(caseTexts);
    emit caseTextsChanged(seqNum, caseTexts);
    item->setText(transLine(item->text()));
}

QString Cabinet::transLine(QString text)
{
    return text.split('|', QString::SkipEmptyParts).join("\n");
}

